package com.xm.security.util;

import com.xm.security.core.DESede;
import com.xm.security.core.RSA;
import com.xm.util.FileUtil;
import com.xm.util.JacksonUtil;
import com.xm.util.old.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 读取解析授权文件（ license.txt ）
 *
 * @author chen-guipeng
 * @date 2022/7/29
 */
public class LicenseUtil {

    protected static final Logger log = LoggerFactory.getLogger(LicenseUtil.class);

    /**
     * 授权信息缓存
     */
    public static Map<String, Object> AUTHORIZE;

    /**
     * 本地设备特征码
     */
    private static String SN;

    /**
     * 存放文件夹位置
     */
    public static final String ENCRYPT_FOLDER = "encrypt";

    /**
     * 读取解析授权文件（ license.txt ）
     */
    @PostConstruct
    public static Map<String, Object> saveAuth() {
        log.info("开始读取解析license文件...................");
        Map<String, Object> resultMap = new HashMap<>(3);
        try {
            AUTHORIZE = null;
//            String filePath = URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("").getPath()) + "license" + File.separator + "license.txt";
//            String filePath = FileUtil.getClassPath("encrypt" + File.separator + "license.txt");
            String filePath = FileUtil.getResourcePath("encrypt/license.txt");
            File file = new File(filePath);
            if (!file.exists()) {
                log.info("license文件路径：" + filePath + " 不存在............");
                return resultMap;
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line = "";
            List<String> licenseList = new ArrayList<>();
            while ((line = br.readLine()) != null) {
                licenseList.add(line);
            }
            br.close();
            if (licenseList.size() < 4) {
                log.info("license文件少于四行，无法解析授权文件.............");
                return resultMap;
            }
            //第一行，Rsa秘钥
            String rsaKey = licenseList.get(0);
            //第二行，Rsa私钥加密后的3des密钥
            String desKey = licenseList.get(1);
            //第三行，3des密钥加密后的设备特征码
            String code = licenseList.get(2);
            //第四行，3des密钥加密后的产品授权信息
            String authorize = licenseList.get(3);
            if (StringUtil.isNullOrEmpty(rsaKey) || StringUtil.isNullOrEmpty(desKey) || StringUtil.isNullOrEmpty(code) || StringUtil.isNullOrEmpty(authorize)) {
                log.info("license文件前四行存在空行，无法解析授权文件...............");
                return resultMap;
            }
            desKey = RSA.decryptByPublicKey(desKey, rsaKey);
            if (StringUtil.isNullOrEmpty(desKey)) {
                log.info("无法解析Rsa私钥加密后的3des密钥...............");
                return resultMap;
            }
            //设备特征码
            code = DESede.des112.decodeString(code, desKey);
            if (StringUtil.isNullOrEmpty(code)) {
                log.info("无法解析3des密钥加密后的设备特征码...............");
                return resultMap;
            }
            //校验设备特征码和本地设备特征码是否一致
            if (StringUtil.isNullOrEmpty(SN)) {
//                SN = MD5.digest.encodeString(security.util.SerialNumberUtil.getCPUAndDisk(String.valueOf(filePath.charAt(0))));
                SN = "ug25f6kzG/uoMuOKPMhnfg==";
            }
            if (!code.equals(SN)) {
                log.info("设备特征码：" + code + " 和本地设备特征码：" + SN + " 不一致...............");
                return resultMap;
            }
            //将授权信息和授权到期时间存入 redis
            authorize = DESede.des112.decodeString(authorize, desKey);
            if (StringUtil.isNullOrEmpty(authorize)) {
                log.info("无法解析3des密钥加密后的产品授权信息...............");
                return resultMap;
            }
            log.info("读取license文件，解析得到授权信息：" + authorize);

            resultMap= JacksonUtil.mapFromJson(authorize, String.class, Object.class);
            if (resultMap != null && resultMap.size() > 0) {
                AUTHORIZE = resultMap;
            }
        } catch (Exception e) {
            log.error("读取解析授权文件异常：", e);
        }
        return resultMap;
    }

}
